﻿using Avalonia.Platform;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using Avalonia.Media.Imaging;

namespace AutojsController.Helpers
{
    public static class Image
    {
        public static Bitmap? LoadFromResource(string imgPath)
        {
            Uri resourceUri;
            if (imgPath.StartsWith("/Assets/"))
            {
                resourceUri = new Uri($"avares://AutojsController{imgPath}");
            }
            else if (imgPath.StartsWith("avares://"))
            {
                resourceUri = new Uri(imgPath);
            }
            else
            {
                return null;
            }
            return new Bitmap(AssetLoader.Open(resourceUri));
        }

        public static async Task<Bitmap?> LoadFromWeb(Uri url)
        {
            using var httpClient = new HttpClient();
            try
            {
                var response = await httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var data = await response.Content.ReadAsByteArrayAsync();
                return new Bitmap(new MemoryStream(data));
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"An error occurred while downloading image '{url}' : {ex.Message}");
                return null;
            }
        }
    }
}
